<template>
  <!-- 加载器 -->
  <Loading v-if="isLoading"></Loading>
  <Form
    class="w-1/3 m-auto mt-40 shadow-2xl shadow-red-300 rounded-box"
    v-if="!isLoading"
    :validation-schema="schema"
    @submit="onSubmit"
  >
    <!-- name -->
    <h1 class="text-4xl text-center pt-4">{{ currentStudent.name }}</h1>
    <!-- 班级 -->
    <label class="input flex gap-2 my-2 w-3/4 mx-auto"
      >Class
      <input
        type="text"
        class="input input-neutra"
        :value="`Class ${currentStudent.class} | Grade ${currentStudent.grade}`"
        disabled
      />
    </label>
    <!-- 分数 -->
    <label class="input flex gap-2 my-2 w-3/4 mx-auto"
      >Score
      <Field
        name="score"
        type="Number"
        class="input input-primary"
        v-model="score"
        min="0"
        max="100"
      />
    </label>
    <ErrorMessage name="score" class="text-red-500 block text-center" />
    <!-- 学科 -->
    <div class="flex gap-2 my-2 w-3/4 mx-auto">
      <Field name="subject" v-slot="{ field }">
        <select v-bind="field" class="select w-full" v-model="subject">
          <option disabled selected>Choose Subject</option>
          <option>Mathematics</option>
          <option>English</option>
          <option>History</option>
          <option>Geography</option>
          <option>Science</option>
          <option>Chemistry</option>
          <option>Physics</option>
          <option>Biology</option>
        </select>
      </Field>
    </div>
    <ErrorMessage name="subject" class="text-red-500 block text-center" />
    <!-- 学期和年份 -->
    <div class="grid grid-cols-2 gap-2 my-2 w-3/4 mx-auto">
      <Field name="semester" v-slot="{ field }">
        <select v-bind="field" class="select" v-model="semesterYear">
          <option disabled>Choose Year</option>
          <option v-for="year in yearList" :key="year">{{ year }}</option>
        </select>
      </Field>
      <ErrorMessage name="subject" class="text-red-500 block text-center" />
      <Field name="semesterSeason" v-slot="{ field }">
        <select v-bind="field" class="select" v-model="semesterSeason">
          <option disabled>Choose Season</option>
          <option>Spring</option>
          <option>Autumn</option>
        </select>
      </Field>
      <ErrorMessage name="subject" class="text-red-500 block text-center" />
    </div>
    <!-- 按钮 -->
    <div class="text-center">
      <button class="btn btn-primary my-2">Update Score</button>
    </div>
  </Form>
</template>
<script setup>
import { getScoreById, updateScore } from "@/services/ApiScore";
import { getStuentByStuentId } from "@/services/ApiStudent";
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useToast } from "vue-toastification";
import Loading from "@/ui/Loading.vue";

import { Field, Form, ErrorMessage } from "vee-validate";
import * as yup from "yup";

const schema = yup.object({
  score: yup
    .number()
    .required("Score is required")
    .integer("Score must be an integer")
    .min(0, "Score must be at least 0")
    .max(100, "Score must be at most 100"),
  subject: yup.string().required("Subject is required"),
  semesterYear: yup.string().required("Year is required"),
  semesterSeason: yup.string().required("Season is required"),
});

const isLoading = ref(true);

const toast = useToast();
const route = useRoute();
const router = useRouter();

const currentStudent = ref({
  name: "name",
  class: "x",
  grade: "x",
});

const score = ref(0);
const subject = ref("English");
const semesterYear = ref("2023");
const semesterSeason = ref("Spring");

const yearList = Array.from(
  { length: new Date().getFullYear() - 2015 + 1 },
  (_, index) => index + 2015
);

onMounted(async () => {
  isLoading.value = true;
  // console.log(route.params.id);
  const scoreList = await getScoreById(route.params.id);
  const scoreData = scoreList[0];
  console.log(scoreData);
  // name.value = scoreData.nam
  score.value = scoreData.score;
  subject.value = scoreData.subject;
  semesterYear.value = scoreData.semester_year;
  semesterSeason.value = scoreData.semester_season;

  const students = await getStuentByStuentId(scoreData.student_id);
  const studentData = students[0];
  // console.log(studentData);
  currentStudent.value = studentData;
  isLoading.value = false;
});

async function onSubmit() {
  toast.info("Score update in progress");
  const newScore = {
    score: score.value,
    subject: subject.value,
    semester_year: semesterYear.value,
    semester_season: semesterSeason.value,
  };

  const scores = await updateScore(route.params.id, newScore);
  console.log(scores);

  router.push({ name: "score" });
  toast.success("Score updated successfully!");
}
</script>
